<?php
/**
 * Created by Gaol Date: 2019/2/16 10:58
 */


namespace app\index\controller;

use app\index\model\Course as CourseModel;
use think\Request;
use think\Session;
use think\Db;
use think\Paginator;


class Course extends Base
{
    //课程列表
    public function  courseList(Request $request)
    {

        $courseName = $request->param("courseName");
        $courseLevel = $request->param("courseLevel");

        $map = [];
        if($courseName) {
            $map['course_name'] = ['like', '%' .$courseName .'%'];
        }
        if($courseLevel && $courseLevel !=1) {
            $map['course_level'] = $courseLevel;
        }
    
        file_put_contents("well.log", $courseLevel, FILE_APPEND | LOCK_EX);

        $courseList = Db::table('course')->where($map)->paginate(8);
        $count = count(Db::table('course')->where($map)->select());

        $list = [];
        foreach($courseList as $course) {
            $course["create_time"] = date("Y-m-d", $course["create_time"]);
            $courseLevel = Db::table('course_level')->where("id", $course["course_level"])->find();
            $course["course_level"] = $courseLevel["level_name"];
            array_push($list,  $course);
        }

        $page = $courseList->render();
        // 模板变量赋值
        $this->assign('courseList', $list);
        $this->assign('page', $page);
        $this->assign('count', $count);
        $this->assign('courseName', $courseName);
        $this->assign('courseLevel', $courseLevel);

        return $this -> view -> fetch('course_list');
    }

    //添加课程  一步棋局
    public function courseAdd()
    {

        return $this->view->fetch('course_add');
    }

    //添加课程  多步棋局
    public function courseMultiAdd(Request $request) {

        return $this->view->fetch('course_multi_add');
    }

    //单步课程创建
    public function saveChess(Request $request) {

        $baseChess = $request->param("baseChess");
        $answerChess = $request->param("answerChess");
        $courseName = trim($request->param("courseName"));
        $courseLevel = $request->param("courseLevel");

        if(!$baseChess) {
            $this->error('请设置基础题设棋谱 :(');
        }

        if(!$answerChess) {
            $this->error('请设置答案棋谱 :(');
        }

        if(!$courseName) {
            $this->error('请填写课程名称 :(');
        }

        $course = new CourseModel;
        $course->base_chess = $baseChess;
        $course->answer_chess = $answerChess;
        $course->course_name = $courseName;
        $course->course_level = $courseLevel;
        $course->create_uid = USER_ID;
        $course->creator = Session::get('user_info')["name"];
        $flag  = $course->save();
        if(false !== $flag) {
            $this->success('课程添加成功 :)');
        }else {
            $this->error('课程添加失败 :(');
        }
    }

    //多步课程创建
    public function saveMultiChess(Request $request) {

        $baseChess = $request->param("baseChess");
        $multiAnswerChess = $request->param("multiAnswerChess");
        $courseName = trim($request->param("courseName"));
        $courseLevel = $request->param("courseLevel");

        //多步答案字符串解析处理  防止末尾出现 ;
        if(substr($multiAnswerChess, -1) == ";") {
            $multiAnswerChess = substr($multiAnswerChess,0,strlen($multiAnswerChess)-1);
        }

        //通过 ; 划分答案棋局的步数
        $chess_step = count(explode(";",$multiAnswerChess));

        if(!$baseChess) {
            $this->error('请设置基础题设棋谱 :(');
        }

        if(!$multiAnswerChess) {
            $this->error('请设置答案棋谱 :(');
        }

        if(!$courseName) {
            $this->error('请填写课程名称 :(');
        }

        $course = new CourseModel;
        $course->chess_step = $chess_step;
        $course->base_chess = $baseChess;
        $course->answer_chess = $multiAnswerChess;
        $course->course_level = $courseLevel;
        $course->course_name = $courseName;
        $course->create_uid = USER_ID;
        $course->creator = Session::get('user_info')["name"];
        $flag  = $course->save();
        if(false !== $flag) {
            $this->success('课程添加成功 :)');
        }else {
            $this->error('课程添加失败 :(');
        }
    }

    //课程删除
    public function courseDelete(Request $request) {
        $courseId = $request->param("id");
        Db::table('course')->delete($courseId);
    }

    //课程分类界面
    public function courseLevelList() {

       $list = Db::table('course_level')->paginate(8);
       $count = count(Db::table('course_level')->select());

        $page = $list->render();
        // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);
       $this->assign('count', $count);

       return $this->view->fetch('course_level_list');
    }

    //课程分类添加界面
    public function courseLevelAdd() {

        $this->view->assign('title','添加课程分类');
        $this->view->assign('keywords','课程');
        $this->view->assign('desc','围棋教务管理系统');

        return $this->view->fetch('course_level_add');
    }

    //课程分类展添加操作
    public function courseLevelDoAdd(Request $request) {

        $courseLevelName = trim($request -> param('courseLevelName'));
        $createTime = date("Y-m-d");

        //已经存在的课程分类数组
        $courseLevelList = Db::table('course_level')->column("level_name");
        if(in_array($courseLevelName, $courseLevelList, true)) {

            return ['status'=> 2, 'message'=> "该课程分类已存在···"];
        }

        $data = [
                  'level_name' => $courseLevelName,
                  'create_time' => $createTime
                ];
        $flag = Db::table('course_level')->insert($data);
        if (true == $flag) {
            $status = 1;
            $message = '恭喜, 添加成功~~';
        }
        return ['status'=>$status, 'message'=>$message];

    }

    //课程分类展次修改界面
    public function courseLevelEdit(Request $request) {

        $courseLevelId = trim($request -> param('id'));

        $courseLevel = Db::table('course_level')->where('id',$courseLevelId)->find();
        $courseLevelName = $courseLevel["level_name"];

        $this->view->assign('courseLevelName', $courseLevelName);
        $this->view->assign('courseLevelId', $courseLevelId);
        return $this->view->fetch('course_level_edit');
    }

    //课程分类展修改操作
    public function courseLevelDoEdit(Request $request) {

        $courseLevelId = $request -> param('courseLevelId');
        $courseLevelName = trim($request -> param('courseLevelName'));
        $createTime = date("Y-m-d");

        //已经存在的课程分类数组
        $courseLevelList = Db::table('course_level')->column("level_name");
        if(in_array($courseLevelName, $courseLevelList, true)) {

            return ['status'=> 2, 'message'=> "该课程分类已存在···"];
        }

        $data = [
            'level_name' => $courseLevelName,
            'create_time' => $createTime
        ];
        $flag = Db::table('course_level')->where("id", $courseLevelId)->update($data);
        if (true == $flag) {
            $status = 1;
            $message = '恭喜, 修改成功~~';
        }
        return ['status'=>$status, 'message'=>$message];
    }

    //课程分类删除
    public function courseLevelDoDelete(Request $request) {

        $courseLevelId = $request->param("id");
        Db::table('course_level')->delete($courseLevelId);
    }


    # 对外前端API #

    //请求课程列表 API
    public function fetchCourseList(Request $request) {

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');

        $courseList = CourseModel::all();

        echo json_encode($courseList, JSON_UNESCAPED_UNICODE);
    }

    //请求课程 API
    public function fetchCourseData(Request $request) {

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');


        $courseId = $request->param("id");
        $course = CourseModel::get($courseId);
        if($course) {
            $res = [
                "status" => 200,
                "data" => $course
            ];
        }else {
            $res = [
                "status" => 404,
                "data" => $course
            ];
        }
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
    }

    //请求课程 API
    public function fetchCourseLevelData(Request $request) {

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');

        $courseLevelList = Db::table('course_level')->select();


        //配合select2.js 字段的严谨设计
        $tempLevel = [];
        $list = [];
        foreach ($courseLevelList as $courseLevel) {

            $tempLevel["id"] = $courseLevel["id"];
            $tempLevel["text"] =  $courseLevel["level_name"];
            array_push($list, $tempLevel);
        }

        if(count($list) > 0) {
            $res = [
                "status" => 200,
                "data" => $list
            ];
        }else {
            $res = [
                "status" => 404,
                "data" => $list
            ];
        }

        echo json_encode($res, JSON_UNESCAPED_UNICODE);
    }

}
